/**
 * Created by yujianfu on 2016/11/10.
 */
import React, {Component, PropTypes} from 'react'
import {
    Tabs,
    Card,
    Table,
    message,
    Button,
    Tag,
    Popover,
    Input,
    Popconfirm,
    Icon, Modal,
} from 'antd'
import Styles from './../Index.less'
import {fetchPost} from './../../../../../utils/request'
import AddRecord from './AddRecord'

class Contacts extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            userId: props.userId,
            tradeNo: props.userId,
            isNBFCAdmin: props.isNBFCAdmin,
            contactNum: 0,
            relationsNum: 0,
            exceptionNum: 0,
            list: [
                // {name: 'name0', inputName: 'inputName0', relation: "relation0", phone: 'mobile通讯录', }
            ],
            calls: [],
            contactSelfItem: null,
            callSelfItem: null,
            loading: false,
            sendList: [],
            content: '',
            selectedRowKeys: [],
            selectRows: [],
            display: false,
            showCalls: props.showCalls,
            item: props.item,
            collectionType: props.collectionType,
        }
    }

    showBook() {
        this.setState({
            display: true,
        })
    };

    componentWillReceiveProps(props) {
        if (this.state.userId != props.userId) {
            let showCalls = true
            if (typeof (props.showCalls) !== 'undefined') {
                showCalls = false
            }

            this.setState({
                display: false,
                outerOverdue: props.outerOverdue,
                showCalls,
                userId: props.userId,
                tradeNo: props.userId,
                item: props.item,
            }, () => {
                this.getData()
            })
        }
    }

    componentDidMount() {
        this.getData()
    }

    getData() {
        if (this.state.tradeNo != null) {
            fetchPost(`/collection/v2/addressbook/contacts/list`, {
                tradeNo: this.state.tradeNo
            }).then(json => {
                if (json.code === 0) {
                    if (json.data != null) {
                        this.setState({
                            contactNum: json.data.contactNum,
                            relationsNum: json.data.relationsNum,
                            exceptionNum: json.data.exceptionNum,
                            calls: json.data.calls,
                            contactSelfItem: json.data.contactSelfItem,
                            callSelfItem: json.data.callSelfItem,
                            selectedRowKeys: [],
                            selectRows: [],
                            list: json.data.list,
                        })
                    }
                } else {
                    message.error(json.msg == null ? 'Get Contacts/Phone Logs Failure' : json.msg)
                }
            })
        }
    }

    showContactTotal() {

        let selfRisk = ''
        return (
            <div style={{display: 'inline-block'}}>
                <font style={{color: '#ec5853', face: 'verdana'}}>Contacts:</font>
                Amount:{this.state.contactNum}&nbsp;&nbsp;
                Relatives:{this.state.relationsNum}&nbsp;&nbsp;
                Abnormal:{this.state.exceptionNum}&nbsp;&nbsp;
                {selfRisk}
            </div>
        )
    }

    showCallTotal() {
        let selfItem = this.state.callSelfItem
        let selfRisk = <font style={{color: 'green', face: 'verdana'}}>Call Records:
            Missing his own number</font>
        if (selfItem != null && selfItem.hit) {
            selfRisk = <font style={{color: 'red', face: 'verdana'}}>Call Records:
                Hit his own number(The name from address book is):{selfItem.name}</font>
        }
        return <div style={{display: 'inline-block'}}>
            {selfRisk}
        </div>
    }

    isShow(record) {
        let mobile = record.phone
        if (mobile.indexOf('-') != -1 || mobile.indexOf('(') != -1 ||
            mobile.length != 11) {
            return true
        }
        return false
    }

    showModal(record) {
        this.setState({
            visible: true,
            addRecordInfo: {
                userCode: this.state.userId,
                tradeNo: this.state.item.tradeNo,
                collectionNo: this.state.item.collectionNo,
                followId: this.state.item.followId,
                followUp: this.state.item.followUp,
                name: record.name,
                mobile: record.phone,
                type: 2,
            }
        })
    };

    handleOk = e => {
        this.getData()
        this.setState({
            visible: false,
        })
    }

    handleCancel = e => {
        this.setState({
            visible: false,
        })
    }

    render() {
        if (this.state.list == null || this.state.userId != this.props.userId) {
            return (
                <div>
                    <Card title={this.showContactTotal()} bodyStyle={{padding: 1}} noHovering={true}>
                        <span className="no-data"><Icon type='frown-o'/>No data</span>
                    </Card>
                </div>
            )
        }

        const columns = [
            {
                title: 'Name',
                key: 'name',
                render: (record) => {
                    if (record.isRelation == 1) {
                        return (<p>{record.name} <Tag color="orange">maybe relatives</Tag></p>)

                    } else {
                        return <p>{record.name}</p>
                    }
                }
            }, {
                title: 'Mobile',
                dataIndex: 'mobile',
                key: 'mobile',
            }, {
                title: 'Last contact time',
                render: (record) => {
                    if (record.lastCallTime) {
                        return (<p>{record.lastCallTime}(<span
                            style={{color: 'red'}}>{record.lastCallDescribe}</span>)</p>)

                    }
                }
            }, {
                title: 'State',
                dataIndex: 'state',
                key: 'state',
            }, {
                title: 'Content record',
                dataIndex: 'collectionContactRecord',
                key: 'collectionContactRecord',
            }, {
                title: 'Phone',
                render: (record) => {
                    return (
                        <Button type='primary' size='small' onClick={() => this.showModal(record)}>Record</Button>
                    )
                },
            }
        ]

        const callsColumns = [
            {
                title: 'Name',
                dataIndex: 'name',
                key: 'name',
            }, {
                title: 'Phone',
                dataIndex: 'phone',
                key: 'phone',
            }, {
                title: 'Call Type',
                dataIndex: 'callType',
                key: 'callType',
            }, {
                title: 'Call Time',
                dataIndex: 'callTime',
                key: 'callTime',
            }, {
                title: 'Call Duration',
                dataIndex: 'callDuration',
                key: 'callDuration',
            },
        ]

        const selectedRowKeys = this.state.selectedRowKeys
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                let selectRows = []
                selectedRows.map(function (item) {
                    let batchMessageItem = {
                        name: item.name,
                        relation: 'Address book friend',
                        mobile: item.phone,
                    }
                    selectRows.push(batchMessageItem)
                })
                this.setState({
                    selectedRowKeys,
                    selectRows,
                })
            },
            getCheckboxProps: (record) => ({
                disabled: this.isShow(record),
            }),
        }

        const hasSelected = selectedRowKeys.length > 0
        return (
            <div className={Styles.detailModule}>
                {!this.state.display && this.state.list.length >= 80
                    ? <Card title={this.showContactTotal()} bodyStyle={{padding: 1}} noHovering={true}>
                        <div style={{
                            width: '100%',
                            height: 400,
                            paddingLeft: '42%',
                            'lineHeight': 34,
                        }}>
              <span style={{color: 'black'}}><Button type='primary'
                                                     onClick={() => {
                                                         this.showBook()
                                                     }}>Click to view contacts</Button></span>
                        </div>
                    </Card>
                    : <Card title={this.showContactTotal()} bodyStyle={{padding: 1}} noHovering={true}>

                        <div style={{maxHeight: 400, overflow: 'scroll'}}>
                            <Table
                                rowKey={record => record.key}
                                pagination={false}
                                bordered
                                dataSource={this.state.list}
                                columns={columns}
                                loading={this.state.loading}
                                size='small'
                            />
                        </div>

                    </Card>
                }

                {this.state.showCalls
                    ? <Card title={this.showCallTotal()} bodyStyle={{padding: 1}} noHovering={true}>
                        <div style={{maxHeight: 150, overflow: 'scroll'}}>
                            <Table
                                pagination={false}
                                bordered
                                dataSource={this.state.calls}
                                columns={callsColumns}
                                loading={this.state.loading}
                                size='small'
                            />
                        </div>
                    </Card>
                    : <span/>
                }
                <Modal
                    title="Record"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    footer={null}
                >
                    <AddRecord onOk={this.handleOk} info={this.state.addRecordInfo}/>
                </Modal>
            </div>

        )
    }
}

export default Contacts
